package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.atguigu.spzx.common.exception.XiaoHeiException;
import com.atguigu.spzx.common.log.annotation.Log;
import com.atguigu.spzx.manager.mapper.SysRoleUserMapper;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.AssginRoleDto;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: SysUserServiceImpl
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/5/16 23:12
 * Version 1.0
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private SysRoleUserMapper sysRoleUserMapper;

    /**
     * 登录方法
     *
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        //获取输入的验证码和存储到redis中key的名称  loginDto获取到
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();

        //2. 根据获取的redis里面的key，查询redis里面存储验证码  set("user:validate" + key）
        String redisCode = (String) redisTemplate.opsForValue().get("user:validate" + key);

        //3. 比较输入的验证码和redis存储验证码是否一致
        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode,captcha)){
            //4. 如果不一致，提示用户，登录失败
            throw new  XiaoHeiException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //5. 如果一致， 删除redis中的验证码
        redisTemplate.delete("user:validate" + key);

        //1. 得到输入的用户民和密码
        String username = loginDto.getUserName();
        String inputPassword = loginDto.getPassword();
        //2. 根据用户名称查询用户
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(username);
        // 3 判断是否为空   空则抛出异常
        if(sysUser == null){
//            throw new RuntimeException("该用户不存在");
            throw new XiaoHeiException(ResultCodeEnum.LOGIN_ERROR);
        }

        //4. 不为空将输入的密码加密和数据库中的密码进行比较
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        //5. 比较密码是否一致
        if(!md5InputPassword.equals(sysUser.getPassword())){
            throw new XiaoHeiException(ResultCodeEnum.LOGIN_ERROR);
//            throw new RuntimeException("密码错误");
        }
        //6. 一致  登录成功   生成TOKEN
        String token = UUID.randomUUID().toString().replace("-","");
        //8. 把登录的用户信息放到redis里存储
        redisTemplate.opsForValue()
                .set("user:login" + token,
                        JSON.toJSONString(sysUser),
                        30, TimeUnit.MINUTES);
        //9、 返回值
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        return loginVo;
    }

    /**
     * 获取当前用户登录信息
     *
     * @param token
     * @return
     */
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = (String) redisTemplate.opsForValue().get("user:login" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    /**
     * 用户退出
     *
     * @param token
     */
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }

    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {

        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list =  sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        //1 判断用户名不能重复
        String inputUserName = sysUser.getUserName();
        SysUser sysUser1 = sysUserMapper.selectUserInfoByUserName(inputUserName);
        if(sysUser1 != null){
            throw new XiaoHeiException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        //2 输入密码加密
        String passwordAfter = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(passwordAfter);

        //设置status的值
        sysUser.setStatus(1);

        sysUserMapper.save(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateUser(sysUser);
    }

    @Override
    public void deleteById(Integer userId) {
        sysUserMapper.deleteById(userId);
    }

    //用户分配角色
    @Log(title = "用户分配角色",businessType = 0)
    @Transactional
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        //1 根据userId删除用户之前分配角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId());

        //2 重新分配新数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        //遍历得到每个角色id
        for(Long roleId : roleIdList){
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(),roleId);
        }
    }
}
